package com.logic.idevice.impl.kjd

import android.os.Handler
import android.os.Message
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import cn.pda.serialport.Tools
import com.handheld.uhfr.UHFRManager
import com.logic.idevice.IUHFScan
import com.sinopec.basemodule.constants.PreferencesConstant
import com.sinopec.basemodule.dialog.TankerProgressDialog
import com.sinopec.basemodule.utils.Util2Sound
import com.sinopec.basemodule.utils.kotlin.NumberUtils
import com.sinopec.basemodule.utils.kotlin.parseInt
import com.sinopec.basemodule.utils.kotlin.validationRfidRule
import com.uhf.api.cls.Reader
import com.uhf.api.cls.Reader.TAGINFO
import com.uhf.uhf.R
import java.math.RoundingMode
import java.util.*

/**
 * @author lwj
 * @ClassName: KjdScan
 * @Description: 汉德霍尔防爆机Kjd手持设备
 */
class KjdScan(
    override val callRefreshText: IUHFScan.IRefreshSpeed,
    override val callDataRefresh: IUHFScan.IRefreshData,
    override val callScanStatusChange: IUHFScan.IScanStatus,
) : IUHFScan {
    val TAG = "Kjd-" + KjdScan::class.java.simpleName
    private var mRfidManager: UHFRManager? = null
    private var RFID_INIT_STATUS = false
    private lateinit var loading: TankerProgressDialog

    //开始扫码时间戳
    private var startTimeMillis = 0L

    //没有过滤的总编码数（计算速度用）
    private var tagTotal = 0

    //速度
    var speed = "0"

    //是否正在扫码
    var isScan = false
    private val codeList = ArrayList<String>()
    var content: AppCompatActivity? = null

    private val MSG_INVENROTY = 1

    private val MSG_INVENROTY_TIME = 1001

    private val handler: Handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            when (msg.what) {
                MSG_INVENROTY -> {

                }
                MSG_INVENROTY_TIME -> {

                }
            }
        }
    }

    override fun init(activity: AppCompatActivity) {
        this.content = activity
        loading = TankerProgressDialog(activity, R.style.CustomDialog)
        loading.setCanceledOnTouchOutside(false)

        activity.lifecycle.addObserver(LifecycleEventObserver { source, event ->
            when (event) {
                Lifecycle.Event.ON_CREATE -> {

                }
                Lifecycle.Event.ON_START -> {
                    initUhf(activity)
                }
                Lifecycle.Event.ON_STOP -> {
                   /* try {
                        Thread.sleep(500)
                    } catch (e: InterruptedException) {
                        e.printStackTrace()
                    }*/
                    //closeModule()
                }
                Lifecycle.Event.ON_RESUME -> {

                }
                Lifecycle.Event.ON_PAUSE -> {

                }
                Lifecycle.Event.ON_DESTROY -> {

                }
                else -> {}
            }
        })
    }

    private fun closeModule() {
        handler.removeCallbacks(invenrotyThread)
        //RFID_INIT_STATUS = false
        if (mRfidManager != null) { //close uhf module
            val isClose = mRfidManager!!.close()
            mRfidManager = null
            Log.d(TAG, "closeModule: rfid close=$isClose")
        }
    }

    override fun startOrStop(isStart: Boolean) {
        callScanStatusChange.onScanStatusChange(isStart)
        if (RFID_INIT_STATUS) {
            //是否正在扫码
            isScan = isStart
            //开始扫码
            if (isStart) {
                Log.d(TAG, "--- startInventory()   ----")
                if (mRfidManager != null) {
                    //启动盘存线程
                    handler.postDelayed(invenrotyThread, 0)
                    //开始扫码时间戳
                    startTimeMillis = System.currentTimeMillis()
                    tagTotal = 0
                    speed = "0"
                }
            } else {
                Log.d(TAG, "--- stopInventory()   ----")
                if (mRfidManager != null) {
                    handler.removeCallbacks(invenrotyThread)
                }
            }
        } else {
            Log.d(TAG, "scanStartBtn  RFID未初始化 ")
        }
    }

    override fun isScanning(): Boolean {
        return isScan
    }

    override fun isCloseRfid(): Boolean {
        closeModule()
        return true
    }

    override fun clear() {
        tagTotal = 0
        codeList.clear()
        callDataRefresh.onRefreshData(codeList)
    }

    override fun newestData(): List<String> {
        return Collections.emptyList()
    }

    private fun initUhf(context: AppCompatActivity) {
        Util2Sound.initSoundPool(context)
        loading.setText("连接设备")
        loading.show()
        // Init Uhf module
        mRfidManager = UHFRManager.getInstance()
        if (mRfidManager != null) {
            loading.dismiss()
            Log.d(TAG, "initRfid()  success.")
            //set uhf module power
            val err: Reader.READER_ERR? = mRfidManager?.setPower(KjdSetting.pow, KjdSetting.pow)
            if (err == Reader.READER_ERR.MT_OK_ERR) {
                RFID_INIT_STATUS = true
                val err1: Reader.READER_ERR? = mRfidManager?.setRegion(Reader.Region_Conf.RG_PRC)
            } else {
                //5101 30db
                //set uhf module power
                val err: Reader.READER_ERR? = mRfidManager?.setPower(30, 30)
                if (err == Reader.READER_ERR.MT_OK_ERR) {
                    RFID_INIT_STATUS = true
                    val err1: Reader.READER_ERR? =
                        mRfidManager?.setRegion(Reader.Region_Conf.RG_PRC)
                } else {
                    Log.d(TAG, "initRfid  fail.")
                }
            }
        } else {
            Log.d(TAG, "initRfid  fail.")
            loading.dismiss()
        }
    }

    private val invenrotyThread: Runnable by lazy {
        object : Runnable {
        override fun run() {
            if (mRfidManager != null) {
                //群读User+epc的方法
                val listTag: List<TAGINFO>? =
                    mRfidManager?.tagEpcOtherInventoryByTimer(50.toShort(),
                        3,
                        0,
                        6,
                        Tools.HexString2Bytes("00000000"))

                if (listTag == null) {
                    Log.d(TAG, "listTag = null")
                    mRfidManager?.asyncStopReading()
                    mRfidManager?.asyncStartReading()
                }
                //
                if (listTag != null && listTag.isNotEmpty()) {
                    Log.d(TAG, "inventory listTag size = " + listTag.size)
                    if (PreferencesConstant.getInstance().beeper_model == 1) {
                        Util2Sound.play(1, 0)
                    }
                    for (taginfo in listTag) {
                        pooled6cData(taginfo)
                    }
                } else {
                    speed = 0.toString()
                }
                handler.postDelayed(this, 0)
            }
        }
    }
    }

    private fun pooled6cData(info: TAGINFO): ArrayList<String> {
        tagTotal++
        var userAndTid = ""
        if (info.EmbededData != null && info.EmbededDatalen > 0) {
            userAndTid = Tools.Bytes2HexString(info.EmbededData, info.EmbededDatalen.toInt())
        }

        if (userAndTid.validationRfidRule()) {
            val scanResultEmp = userAndTid.replace(" ".toRegex(), "")//无空格的
            val scanResult = scanResultEmp.replace("(.{2})(?=.{2})".toRegex(), "$1 ")//两位一空格
            if (!codeList.contains(scanResult)) {
                codeList.add(scanResult)
            }

            val currentTimeMillis = System.currentTimeMillis()
            //计算时间差
            val time = (currentTimeMillis - startTimeMillis) / 1000 //将毫秒转换成秒
            Log.d(TAG, "time=$time")

            if (time > 0) {
                speed = NumberUtils.div(tagTotal.toString(), 0, RoundingMode.DOWN, time.toString())
            }
   /*         if (speed.parseInt() != 0 && PreferencesConstant.getInstance().beeper_model == 1) {
                Util2Sound.play(1, 0)
            }*/
            //ui线程中更新界面
            content!!.runOnUiThread {
                callRefreshText.onRefreshSpeed(
                    codeList.size,
                    speed.parseInt(),
                    0
                )
                callDataRefresh.onRefreshData(codeList)
            }
        }
        return codeList
    }
}